<template>
	<view class="container">
		<view class="topBack"></view>
		<view class="scrollBox">
			<view class="wrap">
				<view class="wTop">
					<view class="wtLeft">
						<image src="https://salephine.asia/img/index/logo.gif" class="headerImg" mode=""></image>
						<view class="name">
							已连续签到<text class="count">{{streak}}</text>天
						</view>
					</view>
					<view class="wtRight">
						<text>签到规则</text>
						<image src="@/pagesMine/static/right-arrow.png" class="icon" mode=""></image>
					</view>
				</view>
				<view class="wMiddle">
					<view
						:class="index==6&&!item.isSign?'sp':item.isSign&&index!=6?'item active':item.isSign&&index==6?'sp active':'item'"
						v-for="(item,index) in signList" :key="index">
						<block v-if="index==6">
							<view class="left">
								<view class="date">
									{{item.date}}
								</view>
								<view class="integral">
									{{item.info}}
								</view>
								<view class="integral">
									{{item.tip}}
								</view>
							</view>
							<view class="right">
								<image src="@/pagesMine/static/box.png" class="icon" mode=""></image>
							</view>
						</block>
						<block v-else>
							<text class="date">{{item.date}}</text>
							<image src="@/pagesMine/static/money.png" class="icon" mode=""></image>
							<text click="integral">{{item.info}}</text>
						</block>
					</view>
				</view>
				<view class="signBtn" @click="openSignModal" :class="{ disabled: isSignedToday }">
					{{ isSignedToday ? '已签到' : '签到' }}
				</view>
			</view>

			<view class="listBox">
				<view class="lTop">
					<view class="left">
						每日任务
					</view>
					<view class="right">
						做任务轻松赚金币
					</view>
				</view>
				<view class="item" v-for="(item,index) in taskList" :key="index">
					<view class="left">
						<image :src="item.icon" class="icon" mode=""></image>
					</view>
					<view class="middle">
						<view class="mTop">
							{{item.name}}
						</view>
						<view class="mBottom">
							<text class="tip">{{item.tip}}</text>
							<image src="@/pagesMine/static/money.png" class="icon" mode=""></image>
							<text class="info">{{item.info}}</text>
						</view>
					</view>
					<view class="right" @click="openModal(item)"
						:class="{ actived: item.actived, disabled: item.isCompleted }">
						{{
							item.remainingSeconds > 0 ? formatTime(item.remainingSeconds) : getStatusName(item.status) 
						}}
					</view>
				</view>
			</view>

			<view class="listBox">
				<view class="lTop">
					<view class="left">
						赚金币
					</view>
					<view class="right">
						做任务轻松赚金币
					</view>
				</view>
				<view class="item">
					<view class="left">
						<image :src="adItem.task_icon" class="icon" mode=""></image>
					</view>
					<view class="middle">
						<view class="mTop">
							{{ adItem.task_name }}   {{ adItem.countInfo }}
						</view>
						<view class="mBottom">
							<text class="tip">{{ adItem.task_tip }}</text>
							<image src="@/pagesMine/static/money.png" class="icon" mode=""></image>
							<text class="info">{{ adItem.task_info }}</text>
						</view>
					</view>
					<view class="right" @click="openAdModal" :class="{ disabled: adItem.completedCount == adItem.daily_limit }">
						{{
							adItem.remainingSeconds > 0 ? formatTime(adItem.remainingSeconds) : '去观看' 
						}}
					</view>
				</view>
			</view>

		</view>

		<tn-modal v-model="signShow" :title="title" :content="content" :button="button" @click="signOnOk"></tn-modal>
		<tn-modal v-model="show" :title="title" :content="content" :button="button" @click="onOk"></tn-modal>
		<tn-modal v-model="adShow" :title="title" :content="content" :button="button" @click="adOnOk"></tn-modal>

	</view>
</template>

<script>
	import {
		getCurrentStreak,
		signIn
	} from "@/apis/sign.js";
	import {
		getTaskList,
		getAdTaskList,
		registerTask,
		checkTask,
		startTask,
		completeTask
	} from "@/apis/task.js";
	import {
		getToken
	} from '@/utils/auth';
	import tool from '@/utils/common.js';

	const TASK_TYPES = {
		SIGN_IN: 'sign_in', // 签到
		DAILY_VIEW_AD: 'daily_view_ad', // 每日观看
		DAILY_SHARE: 'daily_share', // 每日分享
		DAILY_BREAKFAST: 'daily_breakfast',
		DAILY_LUNCH: 'daily_lunch',
		DAILY_DINNER: 'daily_dinner'
	};

	const taskId = `task_${Date.now()}_${Math.floor(Math.random() * 10000)}`;
	export default {
		data() {
			return {
				show: false,
				signShow: false,
				adShow: false,
				title: '提示',
				content: '看广告视频获得奖励，是否播放视频',
				button: [{
						text: '取消',
						backgroundColor: '#E6E6E6',
						fontColor: '#FFFFFF'
					},
					{
						text: '播放',
						backgroundColor: 'tn-bg-indigo',
						fontColor: '#FFFFFF'
					}
				],
				currentItem: null, //当前操作的项
				showAd: getApp().globalData.showAd,
				rewardedVideoAd: null,
				timer: null, // 计时器对象
				adTimer: null, //ad专用
				runningTaskId: null, // 正在执行的任务ID
				streak: 0,
				isSignedToday: false,
				currentTask: {},
				signList: [{
						date: '第1天',
						info: '+1000金币',
						isSign: false
					},
					{
						date: '第2天',
						info: '+1100金币',
						isSign: false
					},
					{
						date: '第3天',
						info: '+1200金币',
						isSign: false
					},
					{
						date: '第4天',
						info: '+1300金币',
						isSign: false
					},
					{
						date: '第5天',
						info: '+1400金币',
						isSign: false
					},
					{
						date: '第6天',
						info: '+1500金币',
						isSign: false
					},
					{
						date: '第7天',
						info: '领取',
						tip: '神秘好礼',
						status: 'special',
						isSign: false
					},
				],
				taskList: [{
						id: 1,
						name: '早饭',
						tip: '任务奖励',
						info: '+1000金币',
						icon: '/pagesMine/static/zaofanicon.png',
						remainingSeconds: 0,
						status: 'not_started'
					},
					{
						id: 2,
						name: '午饭',
						tip: '任务奖励',
						info: '+1000金币',
						icon: '/pagesMine/static/wufanicon.png',
						remainingSeconds: 0,
						status: 'not_started'
					},
					{
						id: 3,
						name: '晚饭',
						tip: '任务奖励',
						info: '+1000金币',
						icon: '/pagesMine/static/wanfanicon.png',
						remainingSeconds: 0,
						status: 'not_started'
					}
				],
				adItem: {
					id: 1,
					name: '广告',
					tip: '任务奖励',
					info: '+1000金币',
					icon: '/pagesMine/static/adicon.png',
					remainingSeconds: 0
				}
			}
		},
		onReady() {

		},
		onShow() {
			if (getToken() !== "") {
				this.getCurrentStreak()
				this.getTaskList()
				this.getAdTaskList()
				this.createAd()
			}
		},
		methods: {
			createAd() {
				// #ifdef APP-PLUS		
					
				if (this.rewardedVideoAd) return;
				const user_Id = uni.getStorageSync('user_Id');
				this.rewardedVideoAd = uni.createRewardedVideoAd({
					adpid: '1520399342',
					urlCallback: { // 服务器回调透传参数1520399342
						userId: user_Id,
						extra: taskId
					}
				}) // 仅用于HBuilder基座调试 adpid: '1507000689'
				this.rewardedVideoAd.onLoad(() => {
					console.log('onLoad event')
					// 当激励视频被关闭时，默认预载下一条数据，加载完成时仍然触发 `onLoad` 事件
				})
				this.rewardedVideoAd.onError((err) => {
					console.log('onError event', err)
				})
				this.rewardedVideoAd.onClose(async (res) => {
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded) {
						// 正常播放结束
						// 这里应该联网给予用户激励。且这段代码应该做安全保护，详见下文中的“安全注意”
						this.pollTaskResult(this.currentTask.id);
					} else {
						// 播放中途退出
						tool.toastTip('中途退出，无法获得奖励，请重新播放')
					}
				})
				// #endif
			},
			openSignModal() {
				if (this.isSignedToday) {
					return; // 如果已签到，不执行后续逻辑
				}
				this.createAd();
				this.signShow = true;
			},
			openModal(item) {
				if (item.isCompleted) {
					return
				}

				if (item.remainingSeconds > 0 || this.adItem.remainingSeconds > 0) {
					uni.showToast({
						title: '请先完成当前任务',
						icon: 'none'
					})
					return
				}

				if (item.status == 'in_progress') {
					completeTask(item.id).then(res => {
						item.isCompleted = true
						item.status == 'completed'
						this.runningTaskId = null
						const {
							points
						} = res;
						tool.toastTip('恭喜获得积分奖励' + points, 'none', 1500);
					})
					return
				}

				// 已有任务进行中或当前任务正在倒计时
				if (this.runningTaskId) {
					uni.showToast({
						title: '请先完成当前任务',
						icon: 'none'
					})
					return
				}

				this.createAd();
				this.currentItem = item;
				this.show = true;
			},
			openAdModal() {
				if (this.adItem.completedCount == this.adItem.daily_limit) {
					return
				}
				if (this.runningTaskId || this.adItem.remainingSeconds > 0) {
					uni.showToast({
						title: '请先完成当前任务',
						icon: 'none'
					})
					return
				}

				this.createAd();
				this.adShow = true;
			},
			onOk(option) {
				this.show = false;
				if (this.currentItem) {
					if (option.index == 1) {
						this.handleTask(this.currentItem);
					}
				}
			},
			signOnOk(option) {
				this.signShow = false;
				if (option.index == 1) {
					this.onSign();
				}
			},
			adOnOk(option) {
				this.adShow = false;
				if (option.index == 1) {
					this.onViewAd();
				}
			},
			async startTask(taskType) {
				if (getToken() === "") {
					uni.navigateTo({
						url: '/pagesExam/login/login'
					})
					return
				}

				// 记录当前任务信息
				this.currentTask = {
					id: taskId,
					type: taskType
				};

				registerTask(this.currentTask).then((res) => {
					this.showAdHandler();
				})
			},
			// 轮询任务结果
			async pollTaskResult(taskId) {
				let retry = 0;
				const maxRetry = 3;

				const check = async () => {

					await checkTask({
						taskId: taskId,
						taskType: this.currentTask.type
					}).then(res => {

						if (res.task.status == 1) {
							// 任务完成，发放前端奖励
							this.giveReward(this.currentTask.type);
							this.currentTask = null;
						} else if (retry < maxRetry) {
							retry++;
							setTimeout(function() {
								check()
							}, 2000); // 2秒后重试
						} else {
							// 超时处理
							uni.showToast({
								title: '验证超时，请联系客服',
								icon: 'none'
							});
						}
					})
				};

				check();
			},
			showAdHandler() {
				this.rewardedVideoAd.show().catch(err => {
					// 错误处理...
					uni.showToast({
						title: "请稍后再试",
						icon: "none"
					});
				});
			},
			giveReward(taskType) {
				let index = 0
				switch (taskType) {
					case TASK_TYPES.SIGN_IN:
						this.isSignedToday = true;
						this.getCurrentStreak();
						tool.toastTip('恭喜获得签到积分奖励', 'none', 1500);
						return;
					case TASK_TYPES.DAILY_VIEW_AD:
						this.getAdTaskList();
						tool.toastTip('恭喜获得积分奖励' + this.adItem.points , 'none', 1500);
						return;
					case TASK_TYPES.DAILY_BREAKFAST:
						index = this.taskList.map(item => item.name).indexOf('早饭');
						break;
					case TASK_TYPES.DAILY_LUNCH:
						index = this.taskList.map(item => item.name).indexOf('午饭');
						break;
					case TASK_TYPES.DAILY_DINNER:
						index = this.taskList.map(item => item.name).indexOf('晚饭');
						break;
				}

				startTask(this.taskList[index].id).then(res => {
					// 开始倒计时（20分钟=1200秒）
					this.taskList[index].remainingSeconds = this.taskList[index].duration
					this.runningTaskId = this.taskList[index].id

					// 启动计时器
					this.timer = setInterval(() => {
						this.taskList[index].remainingSeconds--
						this.taskList[index].actived = true

						// 倒计时结束
						if (this.taskList[index].remainingSeconds <= 0) {
							clearInterval(this.timer)
							this.taskList[index].status == 'in_progress'
							this.taskList[index].remainingSeconds = 0 // 重置倒计时
						}
					}, 1000)
				})
			},
			getCurrentStreak() {
				getCurrentStreak().then(res => {
					const {
						signList,
						streak,
						isSignedToday
					} = res;
					this.signList = signList;
					this.streak = streak;
					this.isSignedToday = isSignedToday;
				})
			},
			getTaskList() {
				getTaskList().then(res => {
					const {
						tasks
					} = res;
					this.taskList = tasks;

					const index = this.taskList.map(item => item.status).indexOf('in_progress');
					if (index > -1) {
						this.taskList[index].actived = true
						this.runningTaskId = this.taskList[index].id
					}

					// 清除可能存在的旧计时器
					if (this.timer) {
						clearInterval(this.timer)
						this.runningTaskId = null
						this.timer = null
					}

					// 创建新计时器
					this.timer = setInterval(() => {
						// 通过find获取最新引用
						const curTask = this.taskList.find(item => item.remainingSeconds > 0)
						if (!curTask) {
							clearInterval(this.timer)
							return
						}

						curTask.remainingSeconds -= 1

						if (curTask.remainingSeconds <= 0) {
							clearInterval(this.timer)
							curTask.remainingSeconds = 0
						}
					}, 1000)
				})
			},
			getAdTaskList() {
				getAdTaskList().then(res => {

					this.adItem = res.tasks;
					this.adItem.countInfo = '    ' + this.adItem.completedCount + '/' + this.adItem.daily_limit + ''

					// 清除可能存在的旧计时器
					if (this.adTimer) {
						clearInterval(this.adTimer)
						this.adTimer = null
					}

					// 创建新计时器
					this.adTimer = setInterval(() => {

						if (!this.adItem.remainingSeconds <= 0) {
							clearInterval(this.adTimer)
							return
						}

						this.adItem.remainingSeconds -= 1

						if (this.adItem.remainingSeconds <= 0) {
							clearInterval(this.adTimer)
							this.adItem.remainingSeconds = 0
						}
					}, 1000)
				})
			},
			onSign() {
				this.startTask(TASK_TYPES.SIGN_IN);
			},
			// 时间格式化（将秒转换为 mm:ss）
			formatTime(seconds) {
				const m = Math.floor(seconds / 60).toString().padStart(2, '0')
				const s = Math.floor(seconds % 60).toString().padStart(2, '0')
				return `${m}:${s}`
			},
			handleTask(item) {
				this.startTask(this.getEatType(item.name));
			},
			onViewAd() {
				this.startTask(TASK_TYPES.DAILY_VIEW_AD);
			},
			getEatType(name) {
				let eatType = '';
				switch (name) {
					case '早饭':
						eatType = 'daily_breakfast'
						break;
					case '午饭':
						eatType = 'daily_lunch'
						break;
					case '晚饭':
						eatType = 'daily_dinner'
						break;
				}
				return eatType;
			},
			getStatusName(status) {
				let statusName = '';
				switch (status) {
					case 'not_started':
						statusName = '去完成'
						break;
					case 'in_progress':
						statusName = '领  取'
						break;
					case 'completed':
						statusName = '已完成'
						break;
				}
				return statusName;
			}
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer)
				this.runningTaskId = null
				this.timer = null
			}
			if (this.adTimer) {
				clearInterval(this.adTimer)
				this.adTimer = null
			}
		}
	}
</script>
<style>
	page {
		margin: 0;
		padding: 0;
		height: 100%;
		width: 100%;
	}

	/* 去掉页面所有滚动条 */
	::-webkit-scrollbar {
		display: none !important;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}
</style>
<style lang="less" scoped>
	// 公共less函数
	.dflex() {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dflexsb() {
		.dflex();
		justify-content: space-between;
	}

	.dflexsa() {
		.dflex();
		justify-content: space-around;
	}

	.container {
		height: 100% !important;
		width: 100% !important;
		background: #f2f3f7 !important;

		.topBack {
			width: 100%;
			height: 500rpx;
			position: fixed;
			top: 0;
			left: 0;
			background: linear-gradient(to bottom, #3da2ff, #f2f3f7);
		}

		.scrollBox {
			width: 100%;
			height: 100% !important;
			position: fixed;
			top: 0;
			left: 0;
			overflow-y: scroll !important;
			background: transparent;
			padding: 30rpx 30rpx 0rpx 30rpx;
			box-sizing: border-box;
		}

		.wrap {
			box-sizing: border-box;
			background: linear-gradient(to bottom, #f3f9fe, #ffffff);
			padding: 20rpx 30rpx;
			border-radius: 26rpx;

			.wTop {
				.dflexsb();

				.wtLeft {
					flex: 1;
					height: 100%;
					.dflex();
					justify-content: flex-start;

					.headerImg {
						width: 70rpx;
						height: 70rpx;
						background: #ccc;
						border-radius: 50%;
						margin-right: 8rpx;
					}

					.name {
						font-size: 28rpx;
						color: #000;
					}

					.count {
						color: #ff371d;
						font-size: 30rpx;
						margin: 0rpx 4rpx;
					}
				}

				.wtRight {
					width: 140rpx;
					color: #ccc;
					font-size: 26rpx;
					.dflexsa();

					.icon {
						width: 28rpx;
						height: 28rpx;
					}
				}
			}

			.wMiddle {
				margin: 10rpx 0rpx;
				padding: 10rpx;
				box-sizing: border-box;
				.dflex();
				justify-content: flex-start;
				flex-wrap: wrap;

				.item {
					height: 166rpx;
					width: 22.75%;
					background: #eff7ff;
					border-radius: 14rpx;
					margin-right: 3%;
					font-size: 24rpx;
					margin-bottom: 20rpx;

					&.active {
						color: #fff !important;
						background: linear-gradient(to bottom, #2ba5fe, #3bb4fd);
					}

					&.active .date {
						color: #fff;
					}

					&:nth-child(4) {
						margin-right: 0 !important;
					}

					.dflex();
					flex-direction: column;

					.date {
						color: #adadad;
					}

					.icon {
						width: 54rpx;
						height: 54rpx;
						margin: 6rpx 0rpx;
					}

					.integral {
						color: #000;
					}
				}

				.sp {
					width: 48.5%;
					height: 166rpx;
					background: #eff7ff;
					border-radius: 14rpx;
					font-size: 24rpx;
					margin-bottom: 20rpx;
					.dflex();
					justify-content: flex-start;

					&.active {
						color: #fff !important;
						background: linear-gradient(to bottom, #2ba5fe, #3bb4fd);
					}

					&.active .date {
						color: #fff !important;
					}

					.left {
						.dflex();
						flex: 1;
						flex-direction: column;
						align-items: flex-start;
						font-size: 24rpx;
						padding-left: 38rpx;
						box-sizing: border-box;

						.date {
							color: #adadad;
						}

						.integral {
							margin: 4rpx 0rpx;
							.dflex();
						}

						.integral:nth-child(2) {
							margin-top: 24rpx;
						}

						.tip {
							color: #000;
						}
					}

					.right {
						width: 52%;
						height: 100%;
						.dflex();

						.icon {
							width: 90rpx;
							height: 90rpx;
						}
					}
				}
			}

			.signBtn {
				background: linear-gradient(to right, #1d9aff, #3cb4ff);
				width: 100%;
				padding: 18rpx 0rpx;
				box-sizing: border-box;
				.dflex();
				color: #fff;
				font-size: 26rpx;
				letter-spacing: 4rpx;
				border-radius: 40rpx;
				margin: 20rpx 0rpx;
			}

			.signBtn.disabled {
				background: #ccc;
				// cursor: not-allowed;
			}
		}

		.listBox {
			box-sizing: border-box;
			background: #fff;
			padding: 20rpx 30rpx;
			border-radius: 26rpx;
			margin: 30rpx 0rpx 80rpx 0rpx;

			.lTop {
				.dflex();
				justify-content: flex-start;
				padding: 10rpx;
				box-sizing: border-box;

				.left {
					font-size: 30rpx;
					color: #000;
					font-weight: bolder;
				}

				.right {
					border-left: 4rpx solid #eee;
					margin-left: 10rpx;
					padding-left: 8rpx;
					box-sizing: border-box;
					font-size: 24rpx;
					color: #ccc;
				}
			}

			.item {
				margin-top: 30rpx;
				width: 100%;
				padding: 10rpx;
				box-sizing: border-box;
				.dflexsb();
				justify-content: flex-start;

				.left {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					background: #ecfaff;
					.dflex();

					.icon {
						width: 56rpx;
						height: 56rpx;
					}
				}

				.middle {
					flex: 1;
					margin-left: 26rpx;
					height: 100%;

					.mTop {
						font-size: 26rpx;
						color: #000;
						font-weight: bolder;
						margin-bottom: 12rpx;
					}

					.mBottom {
						.dflex();
						justify-content: flex-start;

						.tip {
							font-size: 24rpx;
							color: #ccc;
						}

						.icon {
							width: 28rpx;
							height: 28rpx;
							margin: 0rpx 4rpx 0rpx 6rpx;
						}

						.info {
							color: #f60;
							font-size: 24rpx;
						}
					}
				}

				.right {
					padding: 10rpx 20rpx;
					box-sizing: border-box;
					.dflex();
					color: #fff;
					font-size: 26rpx;
					letter-spacing: 2rpx;
					background: linear-gradient(to right, #1d9aff, #3cb4ff);
					border-radius: 40rpx;
					transition: all 0.3s ease;
				}

				/* 执行中状态 */
				.right.actived {
					background: #f60;
					// transform: scale(0.95);
					// opacity: 0.8;
				}

				.right.disabled {
					background: #ccc;
					// cursor: not-allowed;
				}
			}
		}
	}
</style>